<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-row :gutter="10">
            <el-col :span="8">
                <el-input v-model="queryInfo.query" placeholder="请输入搜索姓名" clearable @clear="getUsersList">
                    <el-button class="el-icon-search" slot="append" @click="getUsersList"></el-button>
                </el-input>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="addFormDialogVisible=true">添加用户</el-button>
            </el-col>
        </el-row>
      <el-table :data="usersList" style="width: 100%" stripe border>
        <el-table-column type="index" label="序号" width="width"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="width"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="width"> </el-table-column>
        <el-table-column prop="mobile" label="电话" width="width"> </el-table-column>
        <el-table-column prop="role_name" label="角色" width="width"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="width"> 
            <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeUserState(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="width">
            <template slot-scope="scope">
               <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
               <el-button type="danger" class="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
               <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                   <el-button type="warning" class="el-icon-setting" size="mini" @click="showSetRoles(scope.row)"></el-button>
               </el-tooltip>
               
            </template> 
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" 
      :current-page="this.queryInfo.pagenum" 
      :page-sizes="[1, 4, 8, 10]" :page-size="this.queryInfo.pagesize" 
      layout="total, sizes, prev, pager, next, jumper" :total="this.total"> 
      </el-pagination>

      <!-- 添加用户 -->
      <el-dialog title="添加用户" :visible.sync="addFormDialogVisible" width="50%" >
          <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules" >
              <el-form-item label="姓名" prop="username">
                  <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                  <el-input v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                  <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer">
              <el-button @click="addFormDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
      </el-dialog>
      <!-- 修改用户 -->
      <el-dialog title="修改用户" :visible.sync="editFormDialogVisible" width="50%">
          <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
              <el-form-item label="姓名">
                  <el-input v-model="editForm.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                  <el-input v-model="editForm.mobile"></el-input>
              </el-form-item>
          </el-form>
          <div slot="footer">
              <el-button @click="editFormDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUser">确 定</el-button>
          </div>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="setRoleFormDialogVisible" width="50%">
          <div>
              <p>当前的用户:{{userinfo.username}}</p>
              <p>当前的角色:{{userinfo.role_name}}</p>
              <span>分配新角色:
                  <el-select v-model="selected" placeholder="请选择">
                      <el-option
                          v-for="item in rolesList"
                          :key="item.id"
                          :label="item.roleName"
                          :value="item.id">
                      </el-option>
                  </el-select>
              </span>
          </div>
          <div slot="footer">
              <el-button @click="setRoleFormDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="setRole">确 定</el-button>
          </div>
      </el-dialog>


    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      usersList: [],
      queryInfo: {
        query: "",
        pagesize: 5,
        pagenum: 1,
      },
      total:0,
    //   显示与隐藏添加用户对话框
    addFormDialogVisible:false,
    //添加用户对象绑定
    addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
    },
    //添加用户校验规则
    addFormRules:{
        username:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {pattern:/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        mobile:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '电话格式不正确', trigger: 'blur' }
        ]


    },
    
    // 显示与隐藏修改用户对话框
    editFormDialogVisible:false,
    //修改用户对象绑定
    editForm:{
        // username:'',
        // password:'',
        email:'',
        mobile:''
    },
    //添加用户校验规则
    editFormRules:{
        email:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {pattern:/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '邮箱格式不正确', trigger: 'blur' }
        ],
        mobile:[
            {required: true, message:'请输入用户名', trigger: 'blur'},
            {pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '电话格式不正确', trigger: 'blur' }
        ]


    },
    //显示与隐藏分配角色对话框
    setRoleFormDialogVisible:false,
    userinfo:{},
    rolesList:[],
    selected:null
   
      
    };
  },
  created() {
    this.getUsersList();
  },
  computed: {},
  methods: {
    //    获取用户列表
    async getUsersList() {
      const { data: res } = await this.$http.get("users", { params: this.queryInfo });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      //提示添加用户成功
      this.$message.success("获取用户列表成功");
      this.usersList = res.data.users;
      this.total=res.data.total
    },
    // 分页
    handleSizeChange(pagesize){
        this.queryInfo.pagesize=pagesize
        this.getUsersList()
    },
    handleCurrentChange(pagesize){
        this.queryInfo.pagesize=pagesize
        this.getUsersList()
    },
    // 添加用户
    addUser(){
    this.$refs.addFormRef.validate(async valid=>{
        if(!valid){
            return
        }
        const{data:res}=await this.$http.post('users', this.addForm)
        // console.log(res)
        if(res.meta.status!==201){
        return this.$message.error('添加用户失败')
        }
        //关闭对话框
        this.addFormDialogVisible=false
        //刷新用户列表
        this.getUsersList()
        //提示添加用户成功
        this.$message.success('添加用户成功')
    })
    
    },
    // 监听switch状态改变
    async changeUserState(userinfo){
        console.log(userinfo)
    const{data:res}=await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
    console.log(res)
    if(res.meta.status!==200){
        userinfo.mg_state=!userinfo.mg_state
     return this.$message.error('更新用户状态失败')
    }
     //刷新用户列表
     this.getUsersList()
    //提示添加用户成功
    this.$message.success('更新用户状态成功')
    },
    //显示修改用户对话框
    async showEditDialog(id){
        this.editFormDialogVisible=true
        const{data:res}=await this.$http.get(`users/${id}`)
        if(res.meta.status!==200){
         return this.$message.error('查询用户信息失败')
        }
          //关闭对话框
        //   this.editDialogVisible=false
         //刷新用户列表
        //  this.getUsersList()
        //提示添加用户成功
        this.$message.success('查询用户信息成功')
        // console.log(res)
        this.editForm=res.data
    },
    //修改用户
    editUser(){
        this.$refs.editFormRef.validate(async valid=>{
            if(!valid){
                return
            }
            const{data:res}=await this.$http.put(`users/${this.editForm.id}`,{email:this.editForm.email,mobile:this.editForm.mobile})
        console.log(res)
        if(res.meta.status!==200){
         return this.$message.error('修改用户信息失败')
        }
          //关闭对话框
          this.editFormDialogVisible=false
         //刷新用户列表
         this.getUsersList()
        //提示添加用户成功
        this.$message.success('修改用户信息成功')
        })
        
    },
    // 删除
    async removeUserById(id){
        this.$confirm("确定要删除吗","提示",{
            confirmButtonText:'确定',
            cancelButtonText:'取消',
            type:'warning'
        }).then(async ()=>{
            const{data:res}=await this.$http.delete(`users/${id}`)
            console.log(res)
            this.getUsersList()

        }).catch(()=>{
            this.$message.info('已取消删除')

        })
    },
    // 显示分配角色
    async showSetRoles(userinfo){
        console.log(userinfo)
        this.userinfo=userinfo
        this.setRoleFormDialogVisible=true
        const{data:res}=await this.$http.get('roles')
        console.log(res)
        if(res.meta.status!==200){
         return this.$message.error('获取角色列表失败')
        }
        //提示添加用户成功
        this.$message.success('获取角色列表成功')
        this.rolesList=res.data
    },
    // 分配角色
    async setRole(){
        if(!this.selected){
            return this.$message.error('请选择角色')
        }
        const{data:res}=await this.$http.put(`users/${this.userinfo.id}/role`,{
            rid:this.selected
        })
        console.log(res)
        if(res.meta.status!==200){
         return this.$message.error('分配角色失败')
        }
          //关闭对话框
          this.setRoleFormDialogVisible=false
         //刷新用户列表
         this.getUsersList()
        //提示添加用户成功
        this.$message.success('分配角色成功')
    }

  },
};
</script>
<style lang="less" scoped>
</style>
